package handlers

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"shopback/models"
	"strconv"

	"github.com/gorilla/mux"
)

// AddOrder 用于创建新订单
	// @Summary 向未支付订单添加商品
	// @Description 根据用户ID、商品ID和数量向订单中添加商品
	// @Tags 订单
	// @Accept json
	// @Produce json
	// @Param user_id path int true "用户ID"
	// @Param order_item body models.OrderItem true "订单商品信息"
	// @Success 200 {string} string "商品添加成功"
	// @Failure 400 {string} string "无效的请求参数"
	// @Failure 404 {string} string "订单未找到"
	// @Failure 500 {string} string "服务器内部错误"
	// @Router /orders/{user_id}/items [post]
func AddOrder(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	userID, err := strconv.Atoi(vars["user_id"])
	if err != nil {
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, `{"message": "无效的用户ID"}`, http.StatusBadRequest)
		return
	}

	// 解析请求体
	var requestData struct {
		Items []struct {
			ProductID int     `json:"product_id"`
			Quantity  int     `json:"quantity"`
			Price     float64 `json:"price"`
		} `json:"items"`
	}

	if err := json.NewDecoder(r.Body).Decode(&requestData); err != nil {
		log.Printf("解析请求体失败: %v", err)
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, `{"message": "无效的请求参数"}`, http.StatusBadRequest)
		return
	}

	// 验证请求数据
	if len(requestData.Items) == 0 {
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, `{"message": "订单不能为空"}`, http.StatusBadRequest)
		return
	}

	// 创建订单
	orderID, err := models.CreateOrder(userID)
	if err != nil {
		log.Printf("创建订单失败: %v", err)
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, fmt.Sprintf(`{"message": "创建订单失败: %v"}`, err), http.StatusInternalServerError)
		return
	}

	// 添加订单商品
	for _, item := range requestData.Items {
		if item.ProductID <= 0 || item.Quantity <= 0 {
			w.Header().Set("Content-Type", "application/json")
			http.Error(w, `{"message": "无效的商品ID或数量"}`, http.StatusBadRequest)
			return
		}

		err = models.AddOrderItem(int(orderID), item.ProductID, item.Quantity, item.Price)
		if err != nil {
			log.Printf("添加商品到订单失败: %v", err)
			w.Header().Set("Content-Type", "application/json")
			http.Error(w, fmt.Sprintf(`{"message": "添加商品到订单失败: %v"}`, err), http.StatusInternalServerError)
			return
		}
	}

	// 返回成功消息
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode(map[string]interface{}{
		"message":  "订单创建成功",
		"order_id": orderID,
	})
}

// GetOrder 用于获取订单信息
	// @Summary 获取订单信息
	// @Description 根据用户ID获取订单及订单商品
	// @Tags 订单
	// @Accept json
	// @Produce json
	// @Param user_id path int true "用户ID"
	// @Success 200 {object} models.Order "订单信息"
	// @Failure 400 {string} string "无效的用户ID"
	// @Failure 404 {string} string "订单未找到"
	// @Failure 500 {string} string "服务器内部错误"
	// @Router /orders/{user_id} [get]
func GetOrder(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	userID, err := strconv.Atoi(vars["user_id"])
	if err != nil {
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, `{"message": "无效的用户ID"}`, http.StatusBadRequest)
		return
	}

	// 获取订单信息
	order, orderItems, err := models.GetOrderByUserID(userID)
	if err != nil {
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, `{"message": "获取订单失败"}`, http.StatusInternalServerError)
		return
	}

	// 如果订单为空，返回空订单
	if order.UserID == 0 {
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(map[string]interface{}{
			"order":       models.Order{UserID: userID, Status: "未支付"},
			"order_items": []models.OrderItem{},
		})
		return
	}

	// 返回订单信息
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]interface{}{
		"order":       order,
		"order_items": orderItems,
	})
	
}

// GetAllOrders 获取用户的所有订单
	// @Summary 获取用户的所有订单
	// @Description 根据用户ID获取用户的所有订单及订单商品
	// @Tags 订单
	// @Accept json
	// @Produce json
	// @Param user_id path int true "用户ID"
	// @Success 200 {array} models.Order "用户所有订单的列表"
	// @Failure 400 {string} string "无效的用户ID"
	// @Failure 500 {string} string "服务器内部错误"
	// @Router /orders/{user_id}/all [get]
func GetAllOrders(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	userID, err := strconv.Atoi(vars["user_id"])
	if err != nil {
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, `{"message": "无效的用户ID"}`, http.StatusBadRequest)
		return
	}

	orders, orderItems, err := models.GetAllOrders(userID)
	if err != nil {
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, fmt.Sprintf(`{"message": "%s"}`, err.Error()), http.StatusInternalServerError)
		return
	}

	// 构造响应
	var orderList []map[string]interface{}
	for _, order := range orders {
		items := orderItems[order.ID]
		var totalAmount float64
		for _, item := range items {
			totalAmount += item.Price * float64(item.Quantity)
		}

		orderList = append(orderList, map[string]interface{}{
			"orderId":     order.ID,
			"createTime":  order.OrderDate,
			"status":      order.Status,
			"totalAmount": totalAmount,
			"items":       items,
		})
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(orderList)
}

// 修改评论状态请求结构体
type CommentStatusRequest struct {
	UserID    int `json:"user_id"`
	ProductID int `json:"product_id"`
	OrderID   int `json:"order_id"`
}

// GetLatestOrder 获取用户最新订单
	// @Summary 获取用户最新订单
	// @Description 根据用户ID获取用户最新的订单及订单商品
	// @Tags 订单
	// @Accept json
	// @Produce json
	// @Param user_id path int true "用户ID"
	// @Success 200 {object} models.Order "最新订单信息"
	// @Failure 400 {string} string "无效的用户ID"
	// @Failure 404 {string} string "未找到订单"
	// @Failure 500 {string} string "服务器内部错误"
	// @Router /orders/{user_id}/latest [get]
func GetLatestOrder(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	userID, err := strconv.Atoi(vars["user_id"])
	if err != nil {
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, `{"message": "无效的用户ID"}`, http.StatusBadRequest)
		return
	}

	order, orderItems, err := models.GetLatestOrder(userID)
	if err != nil {
		if err.Error() == "未找到订单" {
			w.Header().Set("Content-Type", "application/json")
			http.Error(w, `{"message": "未找到订单"}`, http.StatusNotFound)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, fmt.Sprintf(`{"message": "%s"}`, err.Error()), http.StatusInternalServerError)
		return
	}

	// 计算总金额
	var totalAmount float64
	for _, item := range orderItems {
		totalAmount += item.Price * float64(item.Quantity)
	}

	// 构造响应
	response := map[string]interface{}{
		"orderId":     order.ID,
		"createTime":  order.OrderDate,
		"status":      order.Status,
		"totalAmount": totalAmount,
		"items":       orderItems,
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(response)
}

// GetOrderByID 获取指定订单的详细信息
	// @Summary 获取指定订单的详细信息
	// @Description 根据用户ID和订单ID获取指定订单的详细信息及订单商品
	// @Tags 订单
	// @Accept json
	// @Produce json
	// @Param user_id path int true "用户ID"
	// @Param order_id path int true "订单ID"
	// @Success 200 {object} models.Order "订单详细信息"
	// @Failure 400 {string} string "无效的用户ID或订单ID"
	// @Failure 403 {string} string "无权访问此订单"
	// @Failure 404 {string} string "订单不存在"
	// @Failure 500 {string} string "服务器内部错误"
	// @Router /orders/{user_id}/items/{order_id} [get]
func GetOrderByID(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	userID, err := strconv.Atoi(vars["user_id"])
	if err != nil {
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, `{"message": "无效的用户ID"}`, http.StatusBadRequest)
		return
	}

	orderID, err := strconv.Atoi(vars["order_id"])
	if err != nil {
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, `{"message": "无效的订单ID"}`, http.StatusBadRequest)
		return
	}

	order, orderItems, err := models.GetOrderByID(orderID)
	if err != nil {
		if err.Error() == "订单不存在" {
			w.Header().Set("Content-Type", "application/json")
			http.Error(w, `{"message": "订单不存在"}`, http.StatusNotFound)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, fmt.Sprintf(`{"message": "%s"}`, err.Error()), http.StatusInternalServerError)
		return
	}

	// 验证订单属于该用户
	if order.UserID != userID {
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, `{"message": "无权访问此订单"}`, http.StatusForbidden)
		return
	}

	// 计算总金额
	var totalAmount float64
	for _, item := range orderItems {
		totalAmount += item.Price * float64(item.Quantity)
	}

	// 构造响应
	response := map[string]interface{}{
		"orderId":     order.ID,
		"createTime":  order.OrderDate,
		"status":      order.Status,
		"totalAmount": totalAmount,
		"items":       orderItems,
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(response)
}

// DeleteOrder 用于删除订单中的商品
	// @Summary 删除订单中的商品
	// @Description 根据用户ID和商品ID删除订单中的商品
	// @Tags 订单
	// @Accept json
	// @Produce json
	// @Param user_id path int true "用户ID"
	// @Param product_id path int true "商品ID"
	// @Success 200 {string} string "商品删除成功"
	// @Failure 400 {string} string "无效的请求参数"
	// @Failure 404 {string} string "商品未找到"
	// @Failure 500 {string} string "服务器内部错误"
	// @Router /orders/{user_id}/items/{product_id} [delete]
// func DeleteOrder(w http.ResponseWriter, r *http.Request) {
// 	vars := mux.Vars(r)
// 	userID, err := strconv.Atoi(vars["user_id"])
// 	if err != nil {
// 		http.Error(w, "无效的用户ID", http.StatusBadRequest)
// 		return
// 	}

// 	productID, err := strconv.Atoi(vars["product_id"])
// 	if err != nil {
// 		http.Error(w, "无效的商品ID", http.StatusBadRequest)
// 		return
// 	}

// 	// 调用模型层的 DeleteFromOrder 函数来从订单中删除商品
// 	rowsAffected, err := models.DeleteFromOrder(userID, productID)
// 	if err != nil {
// 		http.Error(w, "服务器内部错误: "+err.Error(), http.StatusInternalServerError)
// 		return
// 	}

// 	if rowsAffected == 0 {
// 		http.Error(w, "商品未找到", http.StatusNotFound)
// 		return
// 	}

// 	// 返回成功消息
// 	json.NewEncoder(w).Encode(map[string]string{
// 		"message": "商品删除成功",
// 	})
// }

// PayOrder 处理订单支付
	// @Summary 处理订单支付
	// @Description 根据订单ID进行支付，并更新订单状态为“已支付”
	// @Tags 订单
	// @Accept json
	// @Produce json
	// @Param order_id path int true "订单ID"
	// @Success 200 {object} map[string]string "支付成功"
	// @Failure 400 {string} string "无效的订单ID"
	// @Failure 500 {string} string "服务器内部错误"
	// @Router /orders/{order_id}/pay [post]
func PayOrder(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	orderID, err := strconv.Atoi(vars["order_id"])
	if err != nil {
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, `{"message": "无效的订单ID"}`, http.StatusBadRequest)
		return
	}

	// 更新订单状态
	err = models.UpdateOrderStatus(orderID, "已支付")
	if err != nil {
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, fmt.Sprintf(`{"message": "%s"}`, err.Error()), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]string{
		"message": "支付成功",
	})
}

// UpdateCommentStatus 处理函数
	// @Summary 更新订单商品的评论状态
	// @Description 根据用户ID、商品ID和订单ID，更新订单商品的评论状态
	// @Tags 订单
	// @Accept json
	// @Produce json
	// @Param user_id path int true "用户ID"
	// @Param product_id path int true "商品ID"
	// @Param order_id path int true "订单ID"
	// @Success 200 {string} string "评论状态更新成功"
	// @Failure 400 {string} string "无效的请求数据"
	// @Failure 500 {string} string "服务器内部错误"
	// @Router /orders/comment-status/{user_id}/{product_id}/{order_id} [put]
func UpdateCommentStatus(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	UserID, err := strconv.Atoi(vars["user_id"])
	if err != nil {
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, `{"message": "无效的用户ID"}`, http.StatusBadRequest)
		return
	}
	ProductID, err := strconv.Atoi(vars["product_id"])
	if err != nil {
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, `{"message": "无效的商品ID"}`, http.StatusBadRequest)
		return
	}
	OrderID, err := strconv.Atoi(vars["order_id"])
	if err != nil {
		w.Header().Set("Content-Type", "application/json")
		http.Error(w, `{"message": "无效的订单ID"}`, http.StatusBadRequest)
		return
	}

	// 调用 models 层的函数更新评论状态
	err = models.UpdateOrderItemCommentStatus(UserID, ProductID, OrderID)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusOK)
	// 构造响应的消息内容
	responseMessage := fmt.Sprintf("%d号用户%d号订单中的产品%d评论成功", UserID, OrderID, ProductID)
	// 设置响应内容类型为 JSON 或者纯文本
	w.Header().Set("Content-Type", "application/json")

	// 将响应消息写入响应体
	response := map[string]string{"message": responseMessage}
	// 将响应体序列化成 JSON 格式
	jsonResponse, err := json.Marshal(response)
	if err != nil {
		// 如果序列化出错，可以记录错误并返回 500 状态码
		http.Error(w, "内部服务器错误", http.StatusInternalServerError)
		return
	}
	
	w.Write(jsonResponse) // 写入响应体
}